package com.atguigu.uitl;

import com.atguigu.bean.TransientSink;
import com.atguigu.common.GmallConfig;
import lombok.SneakyThrows;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author hjy
 * @create 2023/3/15 11:23
 */
public class ClickHouseUtil {
    public static <T> SinkFunction<T> getSinkFunction(String sql) {
        return JdbcSink.<T>sink(
                sql,
                new JdbcStatementBuilder<T>() {
                    @SneakyThrows
                    @Override
                    public void accept(PreparedStatement preparedStatement, T t) throws SQLException {
                        //拿到t的反射
                        Class<?> aClass = t.getClass();
                        Field[] fields = aClass.getDeclaredFields();
                        int offset=0;
                        for (int i = 0; i < fields.length; i++) {
                            Field field = fields[i];
                            TransientSink annotation = field.getAnnotation(TransientSink.class);
                            //判断一下是否需要跳过这个字段
                            if (annotation!=null){
                                offset++;
                                continue;
                            }
                            field.setAccessible(true);
                            Object value = field.get(t);
                            //放入字段的值，这里如果建表语句的字段顺序和javaBean的字段顺序不一致则要在传入的插入语句中写上字段的顺序
                            preparedStatement.setObject(i-offset+1,value);
                        }
                    }
                },
                JdbcExecutionOptions.builder()
                        .withBatchSize(5)
                        .withBatchIntervalMs(1000L)
                        .build(),
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withDriverName(GmallConfig.CLICKHOUSE_DRIVER)
                        .withUrl(GmallConfig.CLICKHOUSE_URL)
                        .build()

        );
    }
}
